<template>
  <div class="warning-pro-container app-container">
    <div class="content-top">
      <!-- 搜索表单 -->
      <div class="search-wrap">
        <SearchForm :list="[...formList]" @submit="search" @reset="reset"></SearchForm>
      </div>
    </div>
    <div class="content-bottom pl20 pr20">
      <!-- 关键词搜索框、编辑多选、更多筛选 -->
      <div class="searchkey-wrap">
        <div class="left">
          <div class="mr38">
            商品流失预警：<b style="color: #ff9900">{{ total }}</b>
          </div>
          <div style="position: relative">
            <el-input
              class="searchkey-input"
              v-model="postData.form.searchKey"
              @keydown.enter="
                () => {
                  searchType = 1;
                  handelSearch();
                }
              "
              @clear="
                () => {
                  searchType = 1;
                  handelSearch();
                }
              "
              style="width: 320px"
              placeholder="请输入商品名、类目名称搜索"
              clearable
            >
              <template #prepend>
                <el-icon class="el-input__icon" style="cursor: pointer" @click="isShowImgSearch = !isShowImgSearch">
                  <PictureFilled />
                </el-icon>
              </template>
              <template #suffix>
                <el-icon class="el-input__icon">
                  <Search />
                </el-icon>
              </template>
            </el-input>
            <!-- {{ searchType }} -->
            <!-- 图片搜索 -->
            <imgSearch v-show="isShowImgSearch" @submit="imgSearchSubmit" @close="closeImgSearch" />
          </div>
        </div>
        <div class="right">
          <el-checkbox v-model="isOnlyShowAdded" label="只展示已补充商品" @change="isShowAddedChange" />
          <el-divider direction="vertical" />
          <el-button v-if="!isOnlyShowAdded" :type="isEdit ? '' : 'primary'" link @click="cancel(!isEdit)">
            编辑多选
            <el-icon class="ml6">
              <Edit />
            </el-icon>
          </el-button>
          <el-divider direction="vertical" />
          <el-button type="primary" link @click="isOpenAttrFilter = true">
            更多筛选
            <el-icon class="ml6">
              <ArrowRight />
            </el-icon>
          </el-button>
        </div>

        <!-- 图片搜索的时候，显示的属性筛选 -->
        <div class="img-attr-filter" v-if="searchType === 2">
          <div>
            <div class="left">
              <img :src="ImgUrl" alt="" @click="openImgCutter" />
              <ImgCutterMy ref="imgCutterMyRef" :imgUrl="imgCutterUrl" @getCoverImage="getCoverImage" />
            </div>
            <div class="right">
              <!-- <p v-for="index in 100" :key="index">{{ index }}</p> -->
              <div v-if="_filterData.length > 0">
                <div v-for="(item, index) in _filterData" :key="item.stastsId">
                  <div class="attr-item">
                    <p>{{ item.stastsName }}：</p>
                    <el-checkbox-group v-model="imgFilterVal[index]" size="small">
                      <div v-for="(item2, index2) in item.children" class="attr-wrap" :key="index2">
                        <el-checkbox
                          :label="item2.stastsName"
                          :value="item2.stastsId"
                          :key="item2.stastsId"
                          @change="
                            val => {
                              changeAttr2(val, item, item2, index);
                            }
                          "
                        >
                          <template #default>
                            <p class="attr2">{{ item2.stastsName }}({{ item2.productNum || "-" }})</p>
                          </template>
                        </el-checkbox>

                        <div class="attr3 ml4" v-if="item2?.children?.length > 0">
                          <el-select
                            v-model="item2.select3"
                            placeholder="请选择"
                            size="small"
                            clearable
                            style="min-width: 120px"
                            multiple
                            @change="
                              val => {
                                changeAttr3(val, item2, index, index2);
                              }
                            "
                          >
                            <el-option
                              v-for="item3 in item2.children"
                              :key="item3.stastsId"
                              :label="item3.stastsName"
                              :value="item3.stastsId"
                            />
                          </el-select>
                        </div>
                      </div>
                    </el-checkbox-group>
                  </div>
                </div>
              </div>
              <div v-else style="display: flex; justify-content: center; width: 100%">
                <el-empty description="暂无数据" image-size="0" />
              </div>
            </div>
            <el-icon
              @click="
                () => {
                  searchType = 1;

                  //清空图片搜索时的属性筛选 勾选项
                  imgFilterVal.value = [];
                  imgFilterVal3.value = [];
                  //清空抽屉筛选回来所保存的数据
                  _filterValMid3 = [];
                  _filterVal = [];
                  _filterVal3 = [];
                  _brandIds = [];

                  // 清空抽屉组件已有的所有数据
                  attrFilterRef.resetAll();
                  handelSearch();
                }
              "
              style="cursor: pointer"
              ><CloseBold
            /></el-icon>
          </div>
        </div>
      </div>

      <!-- 左侧地区多选、数据列表 -->
      <div style="border-left: 1px solid #d8d8d8">
        <el-container>
          <el-aside :class="{ 'fix-wrap': showSelect }">
            <div>
              <div style="border-radius: 0 0 0 10px">
                <div class="title f18">
                  城市区域预警地图
                  <!-- <div class="gray-btn">
                    <div>已上架总数：{{ pubLicNum }}</div>
                  </div> -->
                </div>
                <el-tree
                  :data="treeData"
                  show-checkbox
                  node-key="areaId"
                  :default-expanded-keys="[]"
                  :default-checked-keys="[]"
                  :props="{
                    children: 'children',
                    label: 'areaName'
                  }"
                  @check="areaCheck"
                />
              </div>

              <!-- <div class="submit-btn">
                <div>
                  <el-button
                    type="primary"
                    @click="$router.push({ path: '/products/pre-selection', query: { type: 'designer' } })"
                  >
                    设计师确认
                  </el-button>
                  <el-button
                    type="primary"
                    @click="$router.push({ path: '/products/pre-selection', query: { type: 'procure' } })"
                  >
                    采购确认
                  </el-button>
                </div>
                <p>
                  您还可加购商品数：{{
                    JSON.stringify(currNode) !== "{}" ? currNode.notSelectNum - checkList.length : selectNum - checkList.length
                  }}
                </p>
              </div> -->
            </div>
          </el-aside>
          <el-main>
            <el-row :gutter="25" :class="searchType === 2 ? 'pt120' : ''">
              <!-- <p class="tips" v-show="showTips && isEdit">
              <span class="text-over">
                数据推荐：以往xxx分类中，销量较好商品位于_价格：25~65，85~120，区间，风格：现代，极简，为主，面料：布艺，定制：支持定制，为主。
              </span>
              <el-icon @click="showTips = !showTips">
                <CloseBold />
              </el-icon>
            </p> -->
              <el-checkbox-group v-loading="loading" v-if="shopList.length > 0" v-model="checkList" @change="handleCheckedChange">
                <el-col :span="6" v-for="(item, index) in shopList" :key="index" class="shop-box">
                  <div>
                    <el-checkbox label="" v-show="isEdit" :value="item.productId" />
                    <div class="top">
                      <div class="img-box">
                        <img :src="item.mainPicUrl" alt="" />
                      </div>
                      <div class="top-left" v-if="item.factoryGrade !== null">
                        {{ store.getDictName("sys_user_sex", item.factoryGrade) }}
                      </div>
                      <div class="bottom-box f12">
                        <div class="go-time f12">上市时间：{{ item.appearTime ? item.appearTime.split(" ")[0] : "-" }}</div>
                        <div class="onsale f12">已售:{{ item.saleNum }}</div>
                      </div>
                    </div>
                    <div class="bottom">
                      <div class="header-title">{{ item.productName }}</div>
                      <div class="header-price">
                        <span>
                          成本价 ¥ <span>{{ item.factoryLowestPrice }}</span></span
                        >
                      </div>
                      <div class="choose-shop">预警日期：{{ item.warnTime || "-" }}</div>
                      <div class="area" @click="changeMask(index, item)">
                        <div class="area-font">
                          <div>预警区域：</div>
                          <div class="area-box" v-for="(items, a) in item.productAreaList" v-show="a < 1" :key="a">
                            {{ items.areaName }}({{ items.planNum }})
                          </div>
                        </div>
                        <div class="area-button f12">
                          <el-icon color="#ff3333"> <MoreFilled /> </el-icon
                          ><el-icon color="#ff3333">
                            <CaretTop />
                          </el-icon>
                        </div>
                      </div>
                      <el-button class="mt18" v-if="isOnlyShowAdded" style="width: 100%" type="info" disabled
                        >已完成补充</el-button
                      >
                      <el-button
                        v-else
                        class="mt18"
                        style="width: 100%"
                        type="primary"
                        @click="
                          () => {
                            currObj = item;
                            _isOpen = true;
                          }
                        "
                        >已完成相似商品补充</el-button
                      >
                      <MaskBox
                        ref="childRef"
                        v-model:maskNum="maskNum"
                        type="error-area"
                        :areaData="item.productAreaList"
                        :num="index"
                        @changeMasks="changeMasksd"
                        :productId="productId"
                      ></MaskBox>
                    </div>
                  </div>
                </el-col>
              </el-checkbox-group>

              <div v-else v-loading="loading" style="display: flex; justify-content: center; width: 100%">
                <el-empty description="暂无数据" />
              </div>
            </el-row>
            <div class="pagination" v-if="shopList.length > 0">
              <el-pagination
                v-model="postData.form.page"
                :page-size="postData.form.size"
                :page-sizes="[12, 24, 48, 96]"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
              />
            </div>
            <div class="select-all-wrap" v-show="isEdit">
              <div>
                <el-checkbox v-model="selectAll" label="全选" :indeterminate="indeterminate" @change="clickSelectAll" />
                <div>
                  <p class="mr16">已选中：{{ checkList.length }}</p>
                  <el-button
                    type="primary"
                    plain
                    :disabled="checkList.length <= 0"
                    @click="
                      () => {
                        _isOpen2 = true;
                      }
                    "
                    >已完成补充</el-button
                  >
                  <el-button type="info" @click="cancel(false)">取消</el-button>
                </div>
              </div>
            </div>
          </el-main>
        </el-container>
      </div>
    </div>

    <!-- 属性筛选 -->
    <cateAttrFilter
      ref="attrFilterRef"
      v-model:isOpen="isOpenAttrFilter"
      :category="categoryList"
      :params="Params"
      @changeAttr="changeAttr"
    />

    <!-- 单条已补充 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpen"
      :message="'温馨提示：请在完成相似商品的补充后在点击，确保每个区域的商品丰富性， 操作此选项后，当前商品预警将被消除，确认已完成补充吗？'"
      @submit="returnSubmit(1)"
    />
    <!-- 批量已补充 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpen2"
      :message="'温馨提示：请在完成相似商品的补充后在点击，确保每个区域的商品丰富性， 操作此选项后，当前商品预警将被消除，确认已完成补充吗？'"
      @submit="returnSubmit(2)"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, onBeforeUnmount, getCurrentInstance, watch } from "vue";
import { RefreshRight, Search, MoreFilled, CaretTop, Edit, ArrowRight, CloseBold } from "@element-plus/icons-vue";
import SearchForm from "@/components/SearchForm";
import {
  getCategoryList,
  getWarnCategoryList,
  getWarnAreaList,
  getWarnList,
  finishSupply,
  imgMarking,
  getWarnStatsList
} from "@/api/products/selection";
import { ElMessage } from "element-plus";
import useCodeArrStore from "@/store/modules/select";
const store = useCodeArrStore();
import cateAttrFilter from "./cateAttrFilter.vue";
import MaskBox from "./MaskBox.vue";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";
import imgSearch from "./imgSearch.vue";
import ImgCutterMy from "@/components/ImgCutterMy";

const emit = defineEmits(["changeTotal"]);
const stepsActive = ref(3);
const formList = ref([
  {
    label: "成本价",
    model: "minPrice-maxPrice",
    type: "numrange",
    labelWidth: "70"
  },
  {
    label: "是否定制",
    model: "customType",
    type: "select",
    data: [
      { label: "不可定制", value: 1 },
      { label: "可定制", value: 2 }
    ],
    labelWidth: "70"
  },
  // {
  //   label: "商品风格",
  //   model: "productStyle",
  //   type: "select",
  //   data: store.getDict("shop_product_style"),
  //   labelWidth: "70",
  //   props: {
  //     label: "dictLabel",
  //     value: "dictValue"
  //   }
  // },
  // {
  //   label: "供应品类",
  //   model: "productStyle",
  //   type: "select",
  //   data: store.getDict("shop_product_style"),
  //   labelWidth: "70",
  //   props: {
  //     label: "dictLabel",
  //     value: "dictValue"
  //   }
  // },
  {
    label: "是否有模型",
    model: "isModel",
    type: "select",
    data: [
      { label: "是", value: "1" },
      { label: "否", value: "0" }
    ],
    labelWidth: "90"
  },
  // {
  //   label: "运营区域",
  //   model: "areaId",
  //   type: "city-select",
  //   labelWidth: "70"
  // },
  {
    label: "市场定位",
    model: "factoryGrade",
    type: "select",
    data: [],
    props: {
      label: "dictLabel",
      value: "dictValue"
    },
    labelWidth: "70"
  },
  {
    label: "线上同款",
    type: "select",
    model: "isOnlineEquivalent",
    data: [
      { label: "有", value: 1 },
      { label: "无", value: 0 }
    ],
    labelWidth: "70"
  }
]);
const total = ref(0);
const postData = reactive({
  form: {
    page: 1,
    size: 12,
    searchKey: ""
  }
});
const treeData = ref([]); //地域
const _areaIds = ref([]); //选中的区域ids
const categoryList = ref([]); //分类
const shopList = ref([]);
const allowSelectList = ref([]); //当前页允许被选中的商品
const checkList = ref([]); //选中的商品ids
const selectAll = ref(false);
const indeterminate = ref(false);
const isEdit = ref(false); //是否进入可选中编辑状态
const loading = ref(false);
const showTips = ref(false);
const isOpenAttrFilter = ref(false); //是否打开更多筛选抽屉
const attrList = ref([]); //筛选属性列表
const _filterValMid3 = ref([]); //用户选中的筛选分类
const _filterVal = ref([]); //用户选中的筛选属性值
const _filterVal3 = ref([]); //用户选中的3级筛选属性值
const _brandIds = ref([]);
const attrFilterRef = ref();
const isOnlyShowAdded = ref(false); //只展示已补充商品
const currObj = ref({}); //单条已补充 obj
const _isOpen = ref(false); //单条已补充
const _isOpen2 = ref(false); //批量已补充
const isShowImgSearch = ref(false); //是否打开图片搜索
const imgCutterMyRef = ref();

onMounted(() => {
  addScroll();
  getTree();
  getPageList();
  getSelectNUm();
  getPublishNums();
  getAttrFilterList();
});
watch(
  () => store.dict,
  val => {
    // console.log("数据字典获取到了", val);
    formList.value.map(item => {
      if (item.model === "productStyle") {
        // 商品风格。下拉数据获取
        item.data = store.getDict("shop_product_style");
      } else if (item.model === "factoryGrade") {
        // 市场定位。下拉数据获取
        item.data = store.getDict("shop_product_factory_grade");
      }
    });
  },
  { deep: true, immediate: true }
);

watch(
  () => isEdit.value,
  val => {
    if (val) {
      showTips.value = true;
    }
  },
  { deep: true }
);

//图片搜索submit回调
const imgFilterVal = ref([]);
const imgFilterVal3 = ref([]);
const searchType = ref(1); //查询类别  1-文字查询 2-图片查询
const imgSearchKey = ref(""); //图片识别出来的关键词
const ImgUrl = ref("");
const imgSearchSubmit = async ({ imgUrl, imgId }) => {
  isShowImgSearch.value = false; //关闭图片搜索
  searchType.value = 2;
  ImgUrl.value = imgUrl;
  await imgMarking({ url: imgUrl }).then(res => {
    if (res.code === 200) {
      imgSearchKey.value = res.data[0]?.value || "";
    }
  });
  handelSearch();
  getImgAttrList();
};
//查询图片搜索对应的筛选属性
const _filterData = ref([]);
const getImgAttrList = () => {
  imgFilterVal.value = [];
  imgFilterVal3.value = [];
  getWarnStatsList({
    ...postData.form,
    ...formData.value,
    isSupplySimilar: isOnlyShowAdded.value ? 1 : 0,
    areaIds: _areaIds.value, //区域筛选ids
    searchKey: searchType.value === 2 ? imgSearchKey.value : postData.form.searchKey,
    categoryIds: []
  }).then(res => {
    if (res.code === 200) {
      // console.log("查询出来的属性列表===", res);
      _filterData.value = res.data;
    }
  });
};

//关闭图片搜索
const closeImgSearch = () => {
  isShowImgSearch.value = false;
};

const imgCutterUrl = ref("");
const openImgCutter = () => {
  imgCutterUrl.value = ImgUrl.value;
  // imgCutterUrl.value = "http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/2024-07-01/222.jpg";
  imgCutterMyRef.value.openCutter();
};
//获取裁剪之后的图片file
const getCoverImage = async file => {
  let cutterImg = {};
  await customUpload(cutterImg, { file: { name: file.fileName, raw: file.file } }, "file");
  console.log("裁剪之后的图片===", cutterImg);
  imgSearchSubmit({ imgUrl: cutterImg.url, imgId: cutterImg.uid });
};

//2级属性筛选
const changeAttr2 = (val, item, item2, index) => {
  // console.log('这是2级属性筛选===', item.children, filterVal.value)

  //二级选中的属性id重新排序，按照接口返回的属性顺序排
  let sortArr = [];
  imgFilterVal.value.map((arr, i) => {
    if (index === i) {
      let Arr = [];
      if (arr) {
        for (let ids of arr) {
          const _index = item.children.findIndex(child => child.stastsId == ids);
          if (_index >= 0) {
            Arr[_index] = ids;
          }
        }
      }
      sortArr[index] = Arr;
    }
  });
  imgFilterVal.value[index] = sortArr[index];

  if (!val) {
    item2.select3 = null;
  }

  let ARR = [];
  for (let attr1 of _filterData.value) {
    for (let attr2 of attr1.children) {
      if (attr2.select3 && attr2.select3?.length > 0) {
        attr2.select3.map(obj => {
          ARR.push(attr2.stastsId + "-" + obj);
        });
      }
    }
  }
  imgFilterVal3.value = ARR;

  imgAttrFilter();
};

// 3级属性筛选
const changeAttr3 = (val, item, index, index2) => {
  console.log("这是3级属性筛选===", _filterData.value);
  if (val) {
    //任意选中一个3级属性，默认选中对应的二级属性
    // console.log(9090909090, imgFilterVal.value, index, index2);
    imgFilterVal.value[index] = imgFilterVal.value[index] || [];
    imgFilterVal.value[index][index2] = item.stastsId;
  }

  let ARR = [];
  for (let attr1 of _filterData.value) {
    for (let attr2 of attr1.children) {
      if (attr2.select3 && attr2.select3?.length > 0) {
        attr2.select3.map(obj => {
          ARR.push(attr2.stastsId + "-" + obj);
        });
      }
    }
  }
  imgFilterVal3.value = ARR;

  imgAttrFilter();
};
//图片搜索，属性筛选查询
const imgAttrFilter = () => {
  const attrIds2 = imgFilterVal.value.flat(); //选中的二级属性ids
  for (let ids2 of attrIds2) {
    const str = imgFilterVal3.value.find(item => typeof item === "string" && item.includes(ids2));
    !str && imgFilterVal3.value.push(ids2);
  }
  postData.form.page = 1;
  getPageList();
};
// =======================================================================================================================

//确认单条已补充，批量已补充
const returnSubmit = type => {
  // 请求返还平台的接口
  let ids = [];
  if (type === 1) {
    // 单条
    _isOpen.value = false;
    ids = [currObj.value.productId];
  } else {
    // 批量
    _isOpen2.value = false;
    ids = checkList.value;
  }
  finishSupply({ productIds: ids }).then(res => {
    if (res.code === 200) {
      // if (type === 1) _isOpen.value = false;
      // if (type === 2) _isOpen2.value = false;
      ElMessage({
        message: "操作成功",
        type: "success"
      });

      getPageList();
      reviewCheck();
      type === 2 && resetChecked();
    } else {
      ElMessage({
        message: res.mag,
        type: "error"
      });
    }
  });
};

//"只展示已补充商品"选中状态变化时
const isShowAddedChange = () => {
  isEdit.value = false;
  resetChecked();

  getPageList();
  getAttrFilterList();
};

// 地域勾选变化时
const areaCheck = (obj, checkObj) => {
  console.log("点击了复选框===", obj, checkObj);
  _areaIds.value = checkObj.checkedKeys;
  handleNodeClick();

  // getPageList();
  // getAttrFilterList();
};

//属性筛选id改变时的回调
const changeAttr = ({ filterValMid3, filterVal, filterVal3, brandIds }) => {
  _filterValMid3.value = filterValMid3;
  _filterVal.value = filterVal;
  _filterVal3.value = filterVal3;
  _brandIds.value = brandIds;

  filterDataSubmit(); //属性筛选接口请求
};

/**
 *用户进行属性值勾选，筛选数据
 * @param init 为false时，不重置当前分页； 为true时，重置当前分页为1
 */
const filterDataSubmit = (init = true) => {
  // 属性值筛选数据
  // console.log("属性值筛选数据", _filterVal.value, _filterVal3.value);
  const attrIds2 = _filterVal.value.flat(); //选中的二级属性ids
  for (let ids2 of attrIds2) {
    const str = _filterVal3.value.find(item => typeof item === "string" && item.includes(ids2));
    !str && _filterVal3.value.push(ids2);
  }
  if (init) postData.form.page = 1;
  getPageList();
};

/**
 * 查询可筛选得分类数据
 */
const Params = ref({}); //整体的筛选条件
const getAttrFilterList = async form => {
  //图片搜索时，查询属性筛选列表数据
  searchType.value === 2 && getImgAttrList();

  // 清空抽屉已有的所有数据
  attrFilterRef.value.resetAll();
  Params.value = {
    ...postData.form,
    ...formData.value,
    isSupplySimilar: isOnlyShowAdded.value ? 1 : 0,
    areaIds: _areaIds.value, //区域筛选ids
    searchKey: searchType.value === 2 ? imgSearchKey.value : postData.form.searchKey
  };

  // await getCategoryList(Params.value).then(res => {
  await getWarnCategoryList(Params.value).then(res => {
    if (res.code === 200) {
      categoryList.value = res.data;
      _filterValMid3.value = []; //清空分类筛选勾选项
      _filterVal.value = []; //清空属性筛选勾选项
      _filterVal3.value = []; //清空属性筛选勾选项
      _brandIds.value = [];
      attrFilterRef.value.reset(); //清空抽屉勾选的属性
      console.log("这是筛选分类列表", categoryList.value);
    }
  });
};

/**
 * 已上架总数
 */
const pubLicNum = ref(0);
const getPublishNums = async () => {
  // const { data } = await getPublishNum();
  // pubLicNum.value = data ?? 0;
};

/**
 *
 * @param data 获取可选商品的数量
 */
const selectNum = ref(0);
const getSelectNUm = () => {
  // getNotSelectNum({
  //   page: 1,
  //   size: 9999,
  //   categoryId: postData.form.categoryId
  // }).then(res => {
  //   if (res.code === 200) {
  //     selectNum.value = res.data;
  //   }
  // });
};

//调用子组件方法获取区域
const childRef = ref(null);
const setLayout = (i, id) => {
  childRef.value[i].getOperateAreaLists(id);
};
const maskNum = ref(-92);
const productId = ref("");
const changeMask = async (num, item) => {
  console.log(item, item.productId);
  maskNum.value = num;
  productId.value = item.productId;
  setLayout(num, item.productId);
};
const changeMasksd = () => {
  maskNum.value = -1;
};

const clickSelectAll = val => {
  console.log("all=====", val, allowSelectList.value);

  const arr = []; //筛选出的非当前页选中项
  if (!val) {
    // 取消全选
    shopList.value.map(item => {
      const index = checkList.value.findIndex(item2 => item2 === item.productId);
      if (index >= 0) {
        checkList.value.splice(index, 1);
      }
    });
  } else {
    // 全选
    checkList.value.map(item => {
      const currPids = shopList.value.map(item2 => item2.productId);
      if (!currPids.includes(item)) {
        arr.push(item);
      }
    });
  }
  console.log(arr, allowSelectList.value);

  checkList.value = val ? [...arr, ...allowSelectList.value] : [...checkList.value];
  indeterminate.value = false;
};
/**
 *
 * @param 点击商品复选框
 */
const handleCheckedChange = value => {
  const arr = [];
  shopList.value.map(item => {
    if (value.includes(item.productId)) {
      arr.push(item.productId);
    }
  });
  const checkedCount = arr.length;
  selectAll.value = checkedCount !== 0 && checkedCount === allowSelectList.value.length;
  indeterminate.value = checkedCount > 0 && checkedCount < allowSelectList.value.length;
};

const cancel = (flag = false) => {
  resetChecked();
  isEdit.value = flag;
};

const resetChecked = () => {
  checkList.value = [];
  selectAll.value = false;
  indeterminate.value = false;
};

const currNode = ref({});
const handleNodeClick = data => {
  // currNode.value = data;
  _filterVal.value = []; //清空属性筛选勾选项
  _filterVal3.value = []; //清空属性筛选勾选项
  _brandIds.value = [];
  attrFilterRef.value.reset(); //清空抽屉勾选的属性
  cancel();
  postData.form.page = 1;
  postData.form.size = 12;
  total.value = 0;
  getPageList();
  getSelectNUm();
  getAttrFilterList();
};

const getTree = async () => {
  await getWarnAreaList(postData.form).then(res => {
    treeData.value = res.data || [];
  });
};

const handelSearch = async () => {
  postData.form.page = 1;
  postData.form.size = 12;
  total.value = 0;
  await getPageList();
  reviewCheck();
  getAttrFilterList();
};

const handleCurrentChange = async val => {
  postData.form.page = val;
  await getPageList();
  reviewCheck();
};
const handleSizeChange = async val => {
  postData.form.size = val;
  await getPageList();
  reviewCheck();
};
const reviewCheck = () => {
  const arr = [];
  shopList.value.map(item => {
    if (checkList.value.includes(item.productId)) {
      arr.push(item.productId);
    }
  });
  handleCheckedChange(arr);
};
const getPageList = async () => {
  console.log("列表查询");
  loading.value = true;
  await getWarnList({
    ...postData.form,
    ...formData.value,
    isSupplySimilar: isOnlyShowAdded.value ? 1 : 0,
    areaIds: _areaIds.value, //区域筛选ids
    categoryIds: _filterValMid3.value, //分类筛选ids
    stastsIdsStr: searchType.value === 2 ? imgFilterVal3.value : _filterVal3.value, //属性筛选ids
    brandIds: _brandIds.value, //品牌id
    searchKey: searchType.value === 2 ? imgSearchKey.value : postData.form.searchKey
  })
    .then(res => {
      const { data } = res;
      shopList.value = data.records || [];
      total.value = data.total;
      emit("changeTotal", total.value);

      // 获取可以加入预选的商品 isSelected == 0
      const arr = shopList.value.map(item => {
        return item.productId;
      });
      allowSelectList.value = arr;

      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
};

/**
 * 点击搜索按钮
 */
const formData = ref({});
const search = form => {
  formData.value = JSON.parse(JSON.stringify(form));
  getPageList();
  getAttrFilterList(formData.value);
};

/**
 * 点击重置按钮的回调
 */
const reset = () => {
  console.log("点击重置表单");
  formData.value = {};
  postData.form.page = 1;
  total.value = 0;
  getPageList();
  getAttrFilterList(formData.value);
};

//监听滚动
const showSelect = ref(false);
const scollNum = ref(0);
const handleScroll = event => {
  // 获取滚动位置
  const currentScrollTop = event.target.scrollTop;
  // 处理distance，比如更新data或者做其他操作
  scollNum.value = currentScrollTop;
  const scrollTop = document.querySelector(".warning-pro-container").scrollTop;
  const searchDomTop = document.querySelector(".content-bottom").offsetTop;
  if (scrollTop >= searchDomTop) {
    showSelect.value = true;
  } else {
    showSelect.value = false;
  }
};
const addScroll = () => {
  const container = document.querySelector(".warning-pro-container");
  container.addEventListener("scroll", handleScroll);
};
const removeScroll = () => {
  const container = document.querySelector(".warning-pro-container");
  container.removeEventListener("scroll", handleScroll);
};
// onUnmounted(() => {
onBeforeUnmount(() => {
  removeScroll();
});

//====================================图片上传========================================================================================
import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
import {
  getFolder,
  _throttle, //节流，多次频繁触发时，只执行第一次
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";

const uploadFile = ref();
const FileList = ref([]);
const docFileList = ref([]);
// const imgIsReady = ref(false);
const handleAvatarChangeIcon = _debounce(async (file, fileList, type = "file") => {
  //选中文件触发的change事件
  console.log("触发文件上传==", fileList);
  const _fileList = fileList.filter(item => item.status === "ready"); //未上传成功的图片
  if (type === "file") {
    FileList.value = fileList;
  }
  for (let item of _fileList) {
    await customUpload(item, { file: item }, type);
  }
}, 100);

/**
 * 上传
 */
const customUpload = async (item, option, type) => {
  // 合并已上传和当前上传文件
  const folder = getFolder();
  const objName = folder + option.file.name;
  await ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("文件上传成功，地址为===", res.fileUrl);
      if (type === "file") {
        item["url"] = res.fileUrl.split("?")[0];
        const UID = Number(String(new Date().getTime()) + String(Math.floor(Math.random() * (999 - 100 + 1)) + 100));
        item["uid"] = option.file.uid || UID;
      }
      item["folder"] = objName;

      // const Option = JSON.parse(JSON.stringify(option));
      // uploadIMG(Option); //图片上传到业务端
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};
</script>

<style lang="scss" scoped>
@mixin flex-end {
  display: flex;
  justify-content: end;
}

@mixin flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

@mixin flex-align {
  display: flex;
  align-items: center;
}
p {
  margin: 0;
  padding: 0;
}
:deep(.el-tree) {
  width: 100%;
  overflow-x: auto;
  padding-bottom: 94px;

  .el-icon.el-tree-node__expand-icon {
    padding-left: 10px;
  }

  .el-tree-node.is-current > .el-tree-node__content {
    background-color: #d9e8ff !important;
    color: #007dff;

    .custom-tree-node i {
      color: #007dff !important;
    }
  }
}

.tips {
  padding: 0 10px;
  line-height: 32px;
  height: 32px;
  background-color: #e0eaff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin: 0 10px 20px 10px;
  border-radius: 4px;

  span {
    display: inline-block;
    flex: 1;
  }

  i {
    width: 16px;
  }
}

.select-all-wrap {
  position: absolute;
  bottom: 0;
  right: 0;
  left: 281px;
  z-index: 2;

  & > div {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: white;
    height: 50px;
    padding: 0 20px;
    box-shadow: 0px -5px 10px 0px rgba(0, 0, 0, 0.1);

    & > div {
      display: flex;
      align-items: center;
    }
  }
}

.fix-wrap {
  position: absolute;
  top: 173px;
  bottom: 0px;
  background-color: white;
  border-radius: 0 0 0 10px;
  border-right: 1px solid #d8d8d8;
  overflow-y: hidden;

  & > div {
    height: 100% !important;
  }

  & > div > div:first-of-type {
    height: 100% !important;
  }
}

.fix-wrap + .el-main {
  margin-left: 260px;
}

.warning-pro-container {
  height: calc(100% - 100px);
  overflow-y: auto;
  padding-top: 0;
  padding-bottom: 0;

  .title {
    padding-left: 14px;
    position: relative;
    color: #131414;
    margin: 25px 0 16px 20px;
    display: flex;
    justify-content: space-between;

    &:before {
      position: absolute;
      content: "";
      left: 0;
      top: 14px;
      width: 6px;
      height: 6px;
      background-color: #409eff;
      border-radius: 50%;
    }

    .gray-btn {
      display: flex;
      font-size: 12px;
      padding-right: 12px;

      & > div {
        padding: 1px 6px;
        height: 22px;
        line-height: 22px;
        background-color: #f0f0f0;
        border-radius: 3px;
        text-align: center;
      }
    }
  }

  .content-top {
    .steps-wrap {
      border-bottom: 2px solid rgba(4, 19, 74, 0.04);
      margin: 0 -20px;
      padding: 20px 0 20px 20px;
    }

    .search-wrap {
      padding: 20px;
      background-color: #f6f8fa;
    }
  }

  .content-bottom {
    margin-top: 20px;
    margin: 0 -20px;

    .searchkey-wrap {
      display: flex;
      justify-content: space-between;
      align-items: center;
      position: sticky;
      top: 0;
      background-color: white;
      border-bottom: 1px solid #d8d8d8;
      padding: 20px 0;
      border-radius: 5px 5px 0 0;
      z-index: 2;
      // position: relative;

      .img-attr-filter {
        position: absolute;
        left: 261px;
        right: 0;
        top: 73px;
        box-shadow: 0px 3px 8px 0px rgba(0, 0, 0, 0.1);
        background-color: white;
        & > div {
          position: relative;
          width: 100%;
          height: 100%;
          overflow-y: auto;
          display: flex;
          .left {
            width: 80px;
            height: 80px;
            position: relative;
            overflow: hidden;
            margin: 20px 0 0 20px;
            & > div {
              width: 80px;
              height: 80px;
              position: absolute;
              top: 0px;
              left: 0;
            }
            img {
              position: absolute;
              width: 100%;
              height: 100%;
              border-radius: 4px;
              z-index: 2;
              cursor: pointer;
            }
          }
          .right {
            flex: 1;
            height: 120px;
            overflow-y: auto;
            padding-left: 18px;
            padding: 20px 50px 20px 20px;
            box-sizing: border-box;
            .el-empty {
              padding: 0;
            }
            .attr-item {
              display: flex;
              margin-bottom: 20px;
              & > p {
                font-size: 14px;
                min-width: 80px;
              }
              .el-checkbox-group {
                display: flex;
                flex-wrap: wrap;
              }
            }

            .attr-wrap,
            .cate-wrap {
              display: flex;
              align-items: center;
              border: 1px solid #dcdfe6;
              border-radius: 4px;
              height: 32px;
              padding: 0 8px;
              margin-bottom: 4px;
              color: #3d3d3d;
              background-color: white;

              .cate3,
              .attr2,
              .attr3 {
                color: #3d3d3d;
                font-size: 12px;
              }
              &:not(:last-of-type) {
                margin-right: 8px;
              }
            }
          }
          .el-icon {
            position: absolute;
            right: 20px;
            top: 20px;
            color: #86909c;
          }
        }
      }

      :deep(.el-input-group__prepend) {
        border-radius: 16px 0 0 16px;
        padding: 0 16px 0 12px;
      }
      :deep(.searchkey-input) {
        .el-input__wrapper {
          border-radius: 0 16px 16px 0;
          background: #f6f8fa;
        }
      }

      & > .left {
        display: flex;
        align-items: center;

        & > div:first-of-type {
          width: 260px;
          height: 32px;
          line-height: 32px;
          background: #f6f8fa;
          box-shadow: inset 2px 3px 7px 0px rgba(3, 56, 129, 0.18);
          border-radius: 4px 4px 4px 4px;
          padding-left: 12px;
          color: #4e5969;
          font-size: 14px;
        }
      }
      & > .right {
        display: flex;
        align-items: center;
        :deep(.el-checkbox__inner) {
          border-radius: 50%;
        }
        :deep(.el-checkbox__label) {
          color: #86909c;
        }
      }
    }

    :deep(.el-aside) {
      width: 260px;
      border-right: 1px solid #d8d8d8;
      padding: 0;
      background-color: white;

      & > div {
        position: relative;
      }

      & > div > div {
        height: calc(100vh - 330px - 135px);
        overflow-y: auto;
      }

      .submit-btn {
        position: fixed;
        height: 95px;
        bottom: 20px;
        width: 258px;
        background-color: white;
        border-radius: 0 0 0 10px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        border-top: 1px solid #dcdfe6;
      }
    }

    :deep(.el-main) {
      background-color: #f6f8fa;
      margin-bottom: 20px;

      .el-checkbox-group {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
      }

      .el-checkbox {
        .el-checkbox__inner {
          border-radius: 50%;
          display: inline-block;
          width: 24px;
          height: 24px;

          &::before {
            text-align: center;
            left: 0px;
            top: 10px;
          }

          &::after {
            font-size: 24px;
            text-align: center;
            left: 8px;
            top: 5px;
            width: 5px;
          }
        }
      }

      .el-col-6 {
        max-width: none;
        display: flex;
        justify-content: center;
      }

      .shop-box {
        .el-checkbox {
          position: absolute;
          left: 10px;
          top: 6px;

          .el-checkbox__inner {
            border-radius: 50%;
            display: inline-block;
            width: 24px;
            height: 24px;

            &::after {
              font-size: 24px;
              text-align: center;
              left: 8px;
              top: 5px;
              width: 5px;
            }
          }
        }

        & > div {
          height: 450px;
          min-width: 294px;
          width: 100%;
          overflow: hidden;
          // margin-right: 25px;
          margin-bottom: 20px;
          position: relative;
          background: #ffffff;
          box-shadow: 4px 5px 16px 0px rgba(4, 19, 74, 0.04);
          border-radius: 10px 10px 10px 10px;

          .top {
            min-width: 294px;
            width: 100%;
            height: 200px;

            .img-box {
              width: 100%;
              height: 100%;
              box-shadow: 4px 0px 4px 0px rgba(4, 19, 74, 0.1);
              border-radius: 10px 10px 10px 10px;

              img {
                width: 100%;
                box-shadow: 4px 0px 4px 0px rgba(4, 19, 74, 0.1);
                border-radius: 10px 10px 10px 10px;
                height: 100%;
              }
            }

            .bottom-box {
              position: absolute;
              top: 0;
              bottom: 90px;
              display: flex;
              padding: 0 10px;
              align-items: center;
              justify-content: space-between;
              width: 100%;
              color: #ffffffbf;
            }
          }

          .bottom {
            padding: 20px 7px 0 12px;

            .header-title {
              font-family:
                Microsoft YaHei,
                Microsoft YaHei;
              font-weight: 700;
              min-height: 50px;
              font-size: 14px;
              color: #3d3d3d;
              margin-bottom: 12px;
              line-height: 24px;
              text-align: left;
              font-style: normal;
              text-transform: none;
              overflow: hidden;
              text-overflow: ellipsis;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
              text-transform: none;
            }

            .header-price {
              font-family:
                Microsoft YaHei,
                Microsoft YaHei;
              font-weight: 400;
              font-size: 14px;
              margin-bottom: 10px;
              color: #4e5969;
              line-height: 24px;
              text-align: left;
              font-style: normal;
              text-transform: none;

              span:nth-child(2) {
                // color: red;
              }
            }

            .choose-shop {
              font-family:
                Microsoft YaHei,
                Microsoft YaHei;
              font-weight: 400;
              font-size: 14px;
              margin-bottom: 10px;
              color: #ff9900;
              line-height: 24px;
              text-align: left;
              font-style: normal;
              text-transform: none;
            }

            .area {
              display: flex;
              align-items: center;
              cursor: pointer;
              justify-content: space-between;
              height: 30px;

              .area-font {
                font-family:
                  PingFang SC,
                  PingFang SC;
                font-weight: 400;
                font-size: 12px;
                color: #ff3333;
                line-height: 22px;
                text-align: left;
                font-style: normal;
                text-transform: none;
                display: flex;
                align-items: center;
                justify-content: center;

                .area-box {
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  padding: 4px 10px;
                  background: #ffe6e6;
                  border-radius: 4px 4px 4px 4px;
                }
              }

              .area-button {
                padding: 6px;
                @include flex-center;
                background: #ffe6e6;
                cursor: pointer;
                border-radius: 4px 4px 4px 4px;
              }
            }
          }
        }
      }

      .pagination {
        display: flex;
        justify-content: flex-end;
        padding-bottom: 20px;
      }
    }
  }
}

:deep(.el-steps) {
  .el-step__icon-inner {
    margin-top: -3px;
  }

  .el-step {
    position: relative;
    flex-basis: 40% !important;

    .el-step__head.is-success {
      border-color: transparent;

      .el-step__line {
        height: 0;
        background-color: transparent;
      }

      .el-step__icon.is-text {
        background-color: #007dff;
        color: white;
      }
    }

    .el-step__head.is-process {
      .el-step__icon.is-text {
        border: none;
        background-color: white;
        color: white;
        border: 1px solid rgba(0, 0, 0, 0.4);
      }
    }

    .el-step__head.is-wait {
      .el-step__icon.is-text {
        border: none;
        background-color: #f2f3f5;
        color: #4e5969;
      }
    }

    .el-step__title.is-wait {
      color: #4e5969;
    }

    .el-step__main {
      position: absolute;
      top: -8px;
      left: 40px;

      .el-step__title {
        font-weight: normal;

        &.is-success {
          color: #4e5969;
        }
      }
    }

    .el-step__line-inner {
      border: none;
    }

    .el-step__line {
      left: 160px;
      right: 25px;
      height: 0px;
      background-color: transparent;
      border-bottom: 1px dashed #d8d8d8;
    }
  }
}
</style>
